package cn.xfdzx.android.apps.shop.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.BreakIterator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.adapter.GoodsLimitListAdapter;
import cn.xfdzx.android.apps.shop.adapter.GoodsLimitListHeadAdapter;
import cn.xfdzx.android.apps.shop.adapter.GoodsLimitListHead_TagAdapter;
import cn.xfdzx.android.apps.shop.adapter.GoodsMiaoShaListAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.GoodsLimitBean;
import cn.xfdzx.android.apps.shop.bean.GoodsMiaoSBean;
import cn.xfdzx.android.apps.shop.contract.GoodsLimitContract;
import cn.xfdzx.android.apps.shop.presenter.GoodsLimitPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ImageGlideUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.SendValidateTimerUtil;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.TimeUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.widget.CornerImageView;
import cn.xfdzx.android.apps.shop.widget.recyclemanager.ScaleLayoutManager;

/*
/* 页面批发商品限时秒杀活动
 */
public class XFDGoodsMiaoShaActivity extends BaseMvpActivity<GoodsLimitPresenter> implements GoodsLimitContract.View, View.OnClickListener {
    private ImageView ivBack;      //标题栏-左边按钮
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView recyclerView;
    private String limit = "10";
    private int page  = 1;
    private RelativeLayout.LayoutParams item_bar;
    private LinearLayout llState;
    private GoodsMiaoShaListAdapter goodsMiaoShaListAdapter;//商品列表
    private List<GoodsLimitBean.DataBean> dataBeans;
    private ImageView img_returntop;//返回顶部
    private int mLastVisiblePosition;//列表最后一个可见视图角标
    private TextView tv_time;//头部第一个条目倒计时
    private TextView tv_state;//头部第一个条目状态
    private CornerImageView img_goods;//头部第一个条目图片
    private TextView tv_title;//头部第一个条目标题
    private TextView tv_newprice;//头部第一个条目新价格
    private TextView tv_oldprice;//头部第一个条目老价格
    private TextView tv_gobuy;//头部第一个条目去抢购
    private RelativeLayout rl_title;
    private ImageView img_titlebg;
    private List<GoodsMiaoSBean.DataBean.GoodsBean> goods;
    private GoodsMiaoSBean.DataBean.GoodsBean goodsBeanFirstDate;
    private long service_time;
    private long start_time;
    private long end_time;
    private RelativeLayout rl_firstitem;
    private int currentActiveState;//0未开始，1进行中，2无库存
    private String good_Id;

    @Override
    public int getLayoutId() {
        return R.layout.activity_goodsmiaosha;
    }

    @Override
    public void initView() {
        mPresenter = new GoodsLimitPresenter();
        mPresenter.attachView(this);
        mRefreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recycle_goodsmiaosha);
        ivBack = findViewById(R.id.iv_back);
        llState = findViewById(R.id.ll_state);
        img_titlebg = findViewById(R.id.img_titlebg);
        img_returntop = findViewById(R.id.img_returntop);
        rl_title = findViewById(R.id.rl_title);

        ivBack.setOnClickListener(this);
        img_returntop.setOnClickListener(this);

        initHigh();
        initRecycle();
        mPresenter.getGoodsMiaoShaList(true,true,limit,page);
        mPresenter.getGoodsLimitListHighSales();

    }


    private void initHigh() {

        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);

        int titleHeight = rl_title.getLayoutParams().height;
        ViewGroup.LayoutParams layoutParams = img_titlebg.getLayoutParams();
        layoutParams.height = item_bar.height+titleHeight;
        img_titlebg.setLayoutParams(layoutParams);

    }

    private void initRecycle() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        goodsMiaoShaListAdapter = new GoodsMiaoShaListAdapter(goods);
        recyclerView.setAdapter(goodsMiaoShaListAdapter);
        View headView  = LayoutInflater.from(this).inflate(R.layout.activity_goodsmiaosha_head, recyclerView, false);

        tv_time = headView.findViewById(R.id.tv_time);
        tv_state = headView.findViewById(R.id.tv_state);
        img_goods = headView.findViewById(R.id.img_goods);
        tv_title = headView.findViewById(R.id.tv_title);
        tv_newprice = headView.findViewById(R.id.tv_newprice);
        tv_oldprice = headView.findViewById(R.id.tv_oldprice);
        tv_gobuy = headView.findViewById(R.id.tv_gobuy);
        rl_firstitem = headView.findViewById(R.id.rl_firstitem);
        rl_firstitem.setOnClickListener(this);
        tv_gobuy.setOnClickListener(this);
        goodsMiaoShaListAdapter.addHeaderView(headView);

        goodsMiaoShaListAdapter.setOnListItemGoBuyListener(new GoodsMiaoShaListAdapter.OnItemOnClickListener() {
            @Override
            public void onItemBuyClick(String goodsId) {
                good_Id = goodsId;
                mPresenter.getGoodsStock(goodsId);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE || newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    // DES: 找出当前可视Item位置
                    RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                    if (layoutManager instanceof LinearLayoutManager) {
                        LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                        //mFirstVisiblePosition = linearManager.findFirstVisibleItemPosition();
                        mLastVisiblePosition = linearManager.findLastVisibleItemPosition();
                        if (mLastVisiblePosition>6){
                            img_returntop.setVisibility(View.VISIBLE);
                        }else {
                            img_returntop.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.e("","");
            }
        });

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                page = 1;
                mPresenter.getGoodsMiaoShaList(true,true,limit,page);

            }
        });


     }

    @Override
    protected void onResume() {
        super.onResume();
//        page = 1;
//        mPresenter.getFollowList(true,true,limit,page);
    }

    @Override
    public void finishRefresh() {
        mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        mRefreshLayout.finishLoadMore(true);//加载完成
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(this);
        }
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void getGoodsLimitListSuccess(GoodsLimitBean bean) {
    }

    @Override
    public void getGoodsLimitListHighSalesSuccess(GoodsLimitBean bean) {
    }

    @Override
    public void getGoodsMiaoShaListSuccess(GoodsMiaoSBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (EmptyUtil.isNotEmpty(bean.getData())){
                service_time = bean.getData().getService_time();
                start_time = bean.getData().getStart_time();
                end_time = bean.getData().getEnd_time();

                tv_time.setText(TimeUtil.millis2String(start_time*1000L,"HH:mm:ss"));
                if (service_time >= start_time && service_time < end_time){
                    mDisableTimeTemp = end_time - service_time;
                    tv_state.setText("进行中");
                    currentActiveState =1;
                    stopTickWork();
                    startTickWork();
                }else {
                    mDisableTimeTemp = start_time - service_time;
                    tv_state.setText("即将开始");
                    currentActiveState =0;
                    stopTickWork();
                    if (mDisableTimeTemp>0){
                        startTickWork();
                    }
                }

                if (page == 1) {
                    mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                        @Override
                        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                            mPresenter.getGoodsMiaoShaList(false, true, limit, page);
                        }
                    });
                    goods = bean.getData().getGoods();
                    if (EmptyUtil.isNotEmpty(goods)) {
                        goodsBeanFirstDate = goods.get(0);
                        goods.remove(0);
                        goodsMiaoShaListAdapter.refreshDatas(goods,currentActiveState);
                        img_goods.setType(CornerImageView.TYPE_ROUND);
                        ImageGlideUtil.loadImage(this,img_goods,goodsBeanFirstDate.getImage());

                        tv_title.setText(goodsBeanFirstDate.getGood_title());
                        tv_newprice.setText(""+goodsBeanFirstDate.getConcessional_price());
                        tv_oldprice.setText("¥"+goodsBeanFirstDate.getOriginal_price());
                        tv_oldprice.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG); //中划线
                        if (goodsBeanFirstDate.getSales_volume()>=goodsBeanFirstDate.getStock()){
                            tv_gobuy.setText("已抢光");
                            tv_gobuy.setBackgroundResource(R.drawable.db2b2b2_r5);
                        }else {
                            if (service_time < start_time || service_time >= end_time){
                                currentActiveState = 0;
                                tv_gobuy.setText("未开始");
                                tv_gobuy.setBackgroundResource(R.drawable.db2b2b2_r5);
                            }else {
                                tv_gobuy.setText("马上抢");
                                tv_gobuy.setBackgroundResource(R.drawable.text_color_golimitbuy);
                            }


                        }
                    }else {
                        mRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                } else {

                    if (EmptyUtil.isEmpty(bean.getData().getGoods())) {
                        mRefreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        goodsMiaoShaListAdapter.addDatas(bean.getData().getGoods());
                        page++;
                    }
                }
            }

        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getGoodsStockSuccess(GoodsMiaoSBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (bean.getData().getStock()>0){
                intent = new Intent(this, XFDGoodsDeatailsActivity.class);
                intent.putExtra("good_id",good_Id+"");
                startActivity(intent);
            }else {
                currentActiveState = 2;
                Toast.makeText(this, "很抱歉，该商品已被抢光", Toast.LENGTH_SHORT).show();
                page = 1;
                mPresenter.getGoodsMiaoShaList(true,true,limit,page);
            }

        } else {
             Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getLimitGoodsStockSuccess(GoodsMiaoSBean bean) {

    }

    @Override
    protected void onDestroy() {
        if (EmptyUtil.isNotEmpty(mPresenter))
        mPresenter.detachView();
        if (null!=mTimer)
        stopTickWork();
        super.onDestroy();
    }

    Intent intent;
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:    //返回按钮点击
                finish();
                break;
            case R.id.img_returntop://返回顶部
                recyclerView.scrollToPosition(0);
                img_returntop.setVisibility(View.GONE);
                break;
            case R.id.tv_gobuy://顶部第一个条目的去购买点击
                if (currentActiveState == 0){
                    Toast.makeText(this, "很抱歉，活动尚未开始", Toast.LENGTH_SHORT).show();
                    return;
                }else if (currentActiveState == 2){
                    Toast.makeText(this, "很抱歉，该商品已被抢光", Toast.LENGTH_SHORT).show();
                    return;
                }
                good_Id = goodsBeanFirstDate.getGood_id()+"";
                mPresenter.getGoodsStock(goodsBeanFirstDate.getGood_id()+"");
                break;
            case R.id.rl_firstitem://顶部第一个条目点击
                intent = new Intent(this, XFDGoodsDeatailsActivity.class);
                intent.putExtra("good_id",goodsBeanFirstDate.getGood_id()+"");
                startActivity(intent);
                break;

        }
    }

    //活动开始前倒计时
    private SendValidateTimerUtil mTimer = new SendValidateTimerUtil();
    private long mDisableTimeTemp = 0;
    private int countDown;//活动倒计时秒数
    /**开启倒计时*/
    public void startTickWork() {

        mTimer.startWork(0, 1000, new SendValidateTimerUtil.SDTimerListener() {
            @Override
            public void onWorkMain() {
                if (service_time>=start_time&&service_time<end_time){
                    tickWork();
                }else {
                    tickWorkFront();
                }

            }

            @Override
            public void onWork() {
            }
        });
        // }
    }

    /**
     * 每秒钟调用一次
     */
    private void tickWork() {
        mDisableTimeTemp--;
        if (mDisableTimeTemp>=0){
            //执行
            tv_time.setText(TimeUtil.formattedTime(mDisableTimeTemp));
        }else {
            page = 1;
            mPresenter.getGoodsMiaoShaList(true,true,limit,page);
//            //执行
//            tv_time.setText(TimeUtil.millis2String(start_time*1000L,"HH:mm:ss"));
//            tv_state.setText("即将开始");

        }
    }

    /**
     * 活动开始前
     * 每秒钟调用一次
     */
    private void tickWorkFront() {
        mDisableTimeTemp--;
        Log.e("service_time",mDisableTimeTemp+"===");
        if (mDisableTimeTemp>=0){
            //执行
        }else {//活动开始请求接口
            page = 1;
            mPresenter.getGoodsMiaoShaList(true,true,limit,page);
        }
    }

    public void stopTickWork() {
        mTimer.stopWork();
        //mDisableTimeTemp = countDown;

    }

}
